<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Service;
use App\Models\Facebook;
use App\Models\Cart;
use Illuminate\Support\Facades\Storage;
use App\Models\Article;
use App\Models\Buy;
use App\Models\MoneyLog;
use App\Models\Withdraw;
use App\Models\CaitCart;
use App\Models\RechargeRecord;
use EasyWeChat\Payment\Application;
use App\User;
use Omnipay\Omnipay;
class UserController extends Controller
{
    /**
     * 保存资料
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveUserInfo(Request $request)
    {
        $data = $request->all();
        $user = Auth::user();
        $user->company_name = $data['company_name'];
        $user->company_address = $data['company_address'];
        $user->contact_name = $data['contact_name'];
        $user->job_name = $data['job_name'];
        $user->team_number = $data['team_number'];
        $user->company_email = $data['company_email'];
        $user->homepage = $data['homepage'];
        $user->save();
        return redirect()->back()->with('status', 1);
    }
    /**
     * 名片管理
     */
    public function myCard()
    {
        $pageList = Cart::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.mycard', compact('pageList'));
    }

	/**
     * 删除名片
     * @param unknown $id
     */
    public function deleteCart($id)
    {
        $service = Cart::findOrFail($id);
        $service->delete();
        return redirect()->back()->with('status', '删除成功.');
    }
    /**
     *
     */

    /**
     * 需求发布
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function sendService(Request $request)
    {
        if($request->isMethod('post'))
        {
            $this->validate($request, [
                'title'=>'required',
                'content'=>'required',
            ], ['required'=>'必须填写.']);
            $service = new Service();
            $service->title = $request->title;
            $service->type = $request->type;
            $service->user_id = Auth::user()->id;
            $service->remark = $request->remark;
            $service->content = htmlspecialchars($request->content);
            $service->save();
            return redirect()->back()->with('status', '新增成功.');
        }
        return view('user.sendservice');
    }

    /***
     * 我的需求
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function myService()
    {
        $pageList = Service::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.myservice', compact('pageList'));
    }
    /**
     * 删除需求
     * @param unknown $id
     */
    public function deleteService($id)
    {
        $service = Service::findOrFail($id);
        $service->delete();
        return redirect()->back()->with('status', '删除成功.');
    }
    /**
     *
     */
    public function dataCenter()
    {
        $pageList = Facebook::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.datacenter', compact('pageList'));
    }
    /**
     * 查看留言以及发布留言
     * @param Request $request
     * @return unknown|string|\Illuminate\Http\RedirectResponse
     */
    public function facebook(Request $request)
    {
        if($request->isMethod('post') && $request->id > 0)
        {
            $res = Facebook::where('user_id', Auth::user()->id)->where('id', $request->id)->first();
            if($res)
            {
                return $res;
            }else {
                return $res['replay'] = '暂无数据.';
            }
        }
        $this->validate($request, [
            'name'=>'required',
            'email'=>'required',
            'company'=>'required',
            'mobile'=>'required',
            'content'=>'required',
            'code' => 'required|size:5|captcha'
        ], ['required'=>'全部必须填写.','code.required' => '验证码必须填写.',
            'code.size' => '验证码长为:size.',
            'code.captcha' => '验证码错误,请点击验证码刷新.',]);
        $service = new Facebook();
        $service->name = $request->name;
        $service->email = $request->email;
        $service->company = $request->company;
        $service->mobile = $request->mobile;
        $service->user_id = Auth::user()->id;
        $service->content = htmlspecialchars($request->content);
        $service->save();
        return redirect()->back()->with('status', '新增成功.');
    }
    /**
     * 用户发送名片
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function sendCart(Request $request)
    {
        if($request->isMethod('post'))
        {
            $this->validate($request, [
                'company'=>'required',
                'name'=>'required',
                'fname'=>'required',
                // 'mobile'=>'required',
                // 'homepage'=>'required',
                'price'=> 'required',
                'content'=>'required',
                'smetas'=>'required',
				// 'remark'=>'required',
            ], ['required'=>'请填写必须填写项.']);
            //处理上传图片
            $res = $this->uploadFilesSmeta($request);

            $cart = new Cart();
            $cart->email = $request->email;
            $cart->company = $request->company;
            $cart->name = $request->name;
            // $cart->mobile = $request->mobile;
            $cart->fname = $request->fname;
            $cart->remark = $request->remark;
            $cart->catid = $request->catid;
            $cart->homepage = $request->homepage;
            $cart->price = $request->price;
            $cart->content = $request->content;
            $cart->attachment = $res;
            $cart->user_id = Auth::user()->id;
            $cart->save();
			//插入栏目关系表
			if(isset($request->catidr) && !empty($request->catidr))
			{
				$data = [];
				foreach($request->catidr as $row)
				{
					$id = intval($row);
					if($id >0)
					{
						$data[] = [
							'catid' => $id,
							'cart_id' => $cart->id,
						];
					}
				}
				if(!empty($data))
				{
					$CaitCart = CaitCart::insert($data);
				}
			}

            return redirect()->back()->with('status', '新增成功.');
        }
        return view('user.sendcart');
    }

    /**
     * 资料以及名片购买
     * @param Request $request
     * @return number[]|string[]
     */
    public function buy(Request $request)
    {
        $this->validate($request, [
            'item_id'=>'required',
            'item_type'=>'required'
        ], ['required'=>'请填写必须填写项.']);

        if($request->item_type == 'cart')
        {
            $model = Cart::where('id', $request->item_id)->first();
        }elseif($request->item_type == 'article') {
            $model = Article::where('id', $request->item_id)->first();
        }
        if(!$model)
        {
            return [
                'status' => 0,
                'msg' => '不存在.'
            ];
        }
        if($model->price <=0)
        {
            return [
                'status' => 0,
                'msg' => '此项目不需要购买，免费观看.'
            ];
        }
        //判断用户是否已经购买
        if(Buy::where('item_id', $request->item_id)->where('item_type', $request->item_type)->where('user_id', Auth::user()->id)->first())
        {
            return [
                'status' => 0,
                'msg' => '您已经购买，请勿重复购买，刷新后观看.'
            ];
        }
        //判断用户余额
        if(Auth::user()->money < $model->price)
        {
            return [
                'status' => 1,
                'msg' => '余额不足，请去充值.'
            ];
        }
        //增加购买记录
        $buy = new Buy();
        $buy->item_id = $request->item_id;
        $buy->item_type = $request->item_type;
        $buy->user_id = Auth::user()->id;
        $buy->money = $model->price;
        $buy->item_id = $request->item_id;
        $buy->save();
        //减去金额
        Auth::user()->decrement('money', $model->price);
		if($request->item_type == 'cart')//为名片购买的时候 计算收益
		{
			//个人收益
			$m = round($model->price*(1-config('kou')),2);
			User::find($model->user_id)->increment('money', $m);
			$log = new MoneyLog();
			$log->user_id = $model->user_id;
			$log->money = $m;
			$log->item_id = $request->item_id;
			$log->item_type = $request->item_type;
			$log->content = '用户购买您的名片['.$model->company.']收入.'.$m.'元';
			$log->save();
			//平台收益记录
			$log = new MoneyLog();
			$log->user_id = 15;
			$log->money = $model->price - $m;
			$log->item_id = $request->item_id;
			$log->item_type = $request->item_type;
			$log->content = '用户购买名片['.$model->company.']收入.'.$log->money.'元';
			$log->save();
		}elseif($request->item_type == 'article')
		{
			//平台收益记录
			$log = new MoneyLog();
			$log->user_id = 15;
			$log->money = $model->price;
			$log->item_id = $request->item_id;
			$log->item_type = $request->item_type;
			$log->content = '用户购买报告下载['.$model->post_title.']收入.'.$model->price.'元';
			$log->save();
		}


        //插入用户金额表
        $log = new MoneyLog();
        $log->user_id = Auth::user()->id;
        $log->money = '-'.$model->price;
        $log->item_id = $request->item_id;
        $log->item_type = $request->item_type;
        $log->content = '购买商品支付.'.$model->price.'元';
        $log->save();



        return [
            'status' => 2,
            'msg' => '购买成功.'
        ];

    }
    /**
     * 展示名片
     * @param Request $request
     * @return number[]|string[]|number[]|string[]|number[][]|NULL[][]|unknown[][][][]
     */
    public function showCart(Request $request)
    {
        $this->validate($request, [
            'item_id'=>'required',
            'item_type'=>'required'
        ], ['required'=>'请填写必须填写项.']);

        if($request->item_type == 'cart')
        {
            $model = Cart::where('id', $request->item_id)->first();
            if(!$model && !$model->buys && $model->user_id != Auth::user()->id && $model->price > 0)
            {
                return [
                    'status' => 0,
                    'msg' => '请购买后查看.'
                ];
            }
            $data = [];
            foreach ($model->attachment as $row)
            {
                $data[] = [
                    'alt' => $row['originalName'],
                    'pid' => $row['filename'],
                    'src' => url($row['url']),
                    'thumb' => url($row['url'])
                ];
            }
            $json = [
                'title' => $model->title,
                'id' => $model->id,
                'start' => 0,
                'data' => $data
            ];
            return [
                'status' => 1,
                'data' => $json,
                'msg' => 'ok.'
            ];
        }else {
            return [
                'status' => 0,
                'msg' => '参数错误.'
            ];
        }
    }


    /**
     * 我的名片
     */
    public function buyRecord()
    {
        $pageList = Buy::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.buyrecord', compact('pageList'));
    }

    public function reCharge(Application $payment, Request $request)
    {
        if($request->isMethod('post'))
        {

            $this->validate($request, [
            'money'=>'required|numeric|min:0',
            'type'=> [
                    'required',
                    \Illuminate\Validation\Rule::in(['1', '2']),
                ]
            ], ['money.required'=>'金额必须填写.','numeric'=> '金额必须大于50.']);
            if($request->type==1)//微信
            {
                $data = [
        					'body' => '纺织名片宝-充值',
        					'out_trade_no' => $this->StrOrderOne(),
        					'total_fee' => $request->money*100,
        					'spbill_create_ip' => $request->getClientIp(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
        					'trade_type' => 'NATIVE'
        				];
        				$result = $payment->order->unify($data);
        				// dd($result);
        				if(isset( $result['result_code']) && $result['result_code'] == 'SUCCESS' && isset($result['return_code']) && $result['return_code'] == 'SUCCESS')
        				{
        					//插入记录表
        					$RechargeRecord = new RechargeRecord();
        					$RechargeRecord->user_id = Auth::user()->id;
        					$RechargeRecord->content = json_encode($result);
        					$RechargeRecord->money = $request->money;
        					$RechargeRecord->out_trade_no = $data['out_trade_no'];
        					$RechargeRecord->type = 'wechat';
        					$RechargeRecord->save();

        					return redirect()->back()->with('wechaturl', $result['code_url'])->with('money', $request->money);
        				}else {
        					return redirect()->back()->with('status', $result['return_msg']);
        				}
            }elseif($request->type==2)//支付宝
            {
                $gateway = Omnipay::create('Alipay_AopPage');
                $gateway->setSignType('RSA2'); //RSA/RSA2
                $gateway->setAppId('2018030702330598');
                $gateway->setPrivateKey('MIIEowIBAAKCAQEAx/YWKgJyyKs84biLID/YB7YhCuotaGDma1YxFb8+p0j8Tj2XmOH+5B2Emrkj+FFS9eU4hNPbAcgw6g6weBEJKGf+kO7nR7Wd6VZ04/ci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e/cg34y6p5tuPyXYBPqyJdjCDrbd6dgghyLe3lYQKBgQDMyF/A+gsWNwZcJek6pqDVtiyOiAZgb6fGmguzDza9/4Z4/MfjeDU5uA23w5z6AOCAnzq+uC8Kg5/2nkXjKcDNbYpuacWVwEUUM5P+J3VLCyLvhrT4bNnC6AbsJ0SyAi17ZtZOLA6Syv4C6+sBd5LLlQdhFaSkhqNJaXbl8GRrkwKBgDWKq+bK+sdC+WX/V2pNPWe23/pIB94Tuqr2zkNha3aW4guHo1QUUHrdPCOt3zj3OJU1EXtA7ZSIFcyFNBsDbORK57/93ayKyDewpkc4Z+oDAelt7+nyTGiKSKJF05wIizZ/z5ika0oTa04zmfhiqBrPpuZAMcnccsSTk6xNdWrM');
                $gateway->setAlipayPublicKey('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx/YWKgJyyKs84biLID/YB7YhCuotaGDma1YxFb8+p0j8Tj2XmOH+5B2Emrkj+FFS9eU4hNPbAcgw6g6weBEJKGf+kO7nR7Wd6VZ04/ciVp8rUR2OUemxItVyw9kWoLjcSdY2Pvw+xun2LCauuid3tU6ev/WvJFwQCRYELvXBP/xED2PDwiRuA4QCIN43b/TMW6T1OxSSIF7BG6TNmsViWRw1A/9E8vS/u4+rrlSwMSw+WbGzHlyefD07yZIdKEP1ywPWyCJ+J7K51k4z71n9LTS/K6NP6iuFLtDsVBC+fgfdiTZFZxbtPrhKgDbRu8X9R16Ozlj8Vu7xq4ZWXMuaVQIDAQAB');
                $gateway->setReturnUrl('http://www.textile-cards.com/user/reCharge');
                $gateway->setNotifyUrl('http://www.textile-cards.com/alipay/notify_url');


				$requests = $gateway->purchase();
				$out_trade_no = $this->StrOrderOne();
				$requests->setBizContent([
					'out_trade_no' => $out_trade_no,
					'total_amount' => $request->money,
					'subject'      => '用户['.Auth::user()->mobile.']充值.'.$request->money.'元',
					'product_code' => 'FAST_INSTANT_TRADE_PAY',
				]);

				/**
				 * @var AopCompletePurchaseResponse $response
				 */
				$response = $requests->send();

				//插入记录表
				$RechargeRecord = new RechargeRecord();
				$RechargeRecord->user_id = Auth::user()->id;
				$RechargeRecord->content = json_encode($response);
				$RechargeRecord->money = $request->money;
				$RechargeRecord->out_trade_no = $out_trade_no;
				$RechargeRecord->type = 'alipay';
				$RechargeRecord->save();



				$redirectUrl = $response->getRedirectUrl();
				//or
				$response->redirect();

            }else{
                return redirect()->back()->with('status','支付出错，请稍后再试.');
            }


        }
        return view('user.recharge');
    }


	public function inCome()
	{
		$pageList = MoneyLog::where('user_id', Auth::user()->id)->where('item_type', 'cart')->where('money', '>', 0)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.income', compact('pageList'));
	}

	public function withdraw(Request $request)
	{
		if($request->isMethod('post'))
        {

            $this->validate($request, [
            'money'=>'required|numeric|min:50',
			'mobile'=>'required',
			'name'=>'required',
			'account'=>'required',
            'accounttype'=> [
                    'required',
                    \Illuminate\Validation\Rule::in(['1', '2']),
                ]
            ], ['required'=>'请填写全部填写项.','numeric'=>'必须填写数字','min'=> '金额必须大于50.']);
			//判断余额
			if(Auth::user()->money < (int)$request->money)
			{
				return redirect()->back()->with('status','余额不足.');
			}
			//判断正确申请的提现
			if(Withdraw::where('status', 0)->where('user_id', Auth::user()->id)->first())
			{
				return redirect()->back()->with('status','您已经提现，请耐心等待.');
			}

			$Withdraw = new Withdraw();
			$Withdraw->mobile = $request->mobile;
			$Withdraw->name = $request->name;
			$Withdraw->account = $request->account;
			$Withdraw->accounttype = $request->accounttype;
			$Withdraw->money = (int)$request->money;
			$Withdraw->user_id = Auth::user()->id;
			$Withdraw->save();

            return redirect()->back()->with('status','申请成功，系统将在1-2工作日内处理.');



        }
		return view('user.withdraw');
	}

	public function withdrawRecord()
	{
		$pageList = Withdraw::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.withdraw1', compact('pageList'));
	}


	/**
     * 生成订单号
     * @return string
     */
    protected function StrOrderOne(){
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 上传图片
     * @param unknown $request
     */
    protected function uploadFilesSmeta(Request $request)
    {
        $result = [];
        if ($request->hasFile('smetas')) {
            //
            $files     = $request->file('smetas');
            $disk = Storage::disk('admin');
            foreach ($files as $file)
            {
                if ($file->isValid()) {

                    // 获取文件相关信息
                    $originalName = $file->getClientOriginalName();
                    $ext          = $file->getClientOriginalExtension();
                    $realPath     = $file->getRealPath();
                    $type         = $file->getClientMimeType();
                    $filename     = md5(uniqid()) . '.' . $ext;

                    $bool         = $disk->put('cart/'.$filename, file_get_contents($realPath));

                    if ($bool) {
                        $result[] = [
                            'url' => ('upload/cart/' . $filename),
                            'ext' => $ext,
                            'type' => $type,
                            'originalName' => $originalName,
                            'filename' => $filename
                        ];
                    }
                }
            }
        }
        return $result;

    }
}
